package com.tianyadu.mmall.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyadu.mmall.core.conf.SecurityConstantsConfig;
import com.tianyadu.mmall.core.enums.LoginResponseTypeEnum;
import com.tianyadu.mmall.core.properties.MallSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权认证成功处理器
 *
 * @author xueyj
 * @date 2019-11-04 16:31
 */
@Slf4j
@Component
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MallSecurityProperties mallSecurityProperties;

    /**
     * 授权认证成功处理。
     * 若认证成功，则将authentication信息写回到response
     *
     * @param request        HttpServletRequest
     * @param response       HttpServletResponse
     * @param authentication 权限信息
     * @author xueyj
     * @date 2019/11/4-16:34
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        // 判断是用哪一种方式进行登录, 若请求格式为json，则返回相应json响应信息，否则调用父类返回默认请求响应信息
        if (LoginResponseTypeEnum.JSON.equals(mallSecurityProperties.getBrowser().getLoginType())) {
            //  设置响应信息的格式及字符编码
            response.setContentType(SecurityConstantsConfig.CONTENT_TYPE_JSON);
            //  将响应信息写入至response
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}